package adminLogic

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
)

func GetChildrenRoleIds(ctx context.Context, adminId int64, withself ...bool) []interface{} {
	with := false
	if len(withself) > 0 {
		with = withself[0]
	}
	adminRoleIds := GetRoleIdsByAdminId(ctx, adminId)
	roles := getRoles(ctx)
	tree := utils.NewTree().Init(roles)
	data := []interface{}{}
	for _, roleId := range adminRoleIds {
		data = append(data, tree.GetChildrenIds(roleId, with)...)
	}
	return data
}

func GetRoleIdsByAdminId(ctx context.Context, adminId int64) []interface{} {
	Db := database.Db.GetDefaultDb(ctx)
	rows, e := Db.Query("select role_id from admin_role_access where admin_id=?", adminId)
	if e != nil {
		panic(e)
	}
	return utils.ArrayColumn(rows, "role_id")
}

func GetChildrenRoleAdminIds(ctx context.Context, adminId int64, withself ...bool) []interface{} {
	roleIds := GetChildrenRoleIds(ctx, adminId, withself...)
	return GetChildrenAdminIdsByRoleIds(ctx, roleIds, adminId, withself...)
}

func GetChildrenAdminIdsByRoleIds(ctx context.Context, roleIds []interface{}, adminId interface{}, withself ...bool) []interface{} {
	with := false
	if len(withself) > 0 {
		with = withself[0]
	}

	if len(roleIds) == 0 {
		if with {
			return []interface{}{
				adminId,
			}
		}
		return []interface{}{}
	}

	adminRoleAccess, e := database.Db.GetDefaultDb(ctx).Query("select admin_id from admin_role_access where role_id in (?) group by admin_id", roleIds)

	if e != nil {
		panic(e)
	}

	adminIds := utils.ArrayColumn(adminRoleAccess, "admin_id")

	if with {
		adminIds = append(adminIds, adminId)
	} else {
		adminIds = utils.ArrayFilter(adminIds, func(val interface{}) bool {
			return fmt.Sprintf("%v", val) != fmt.Sprintf("%v", adminId)
		})
	}

	return adminIds
}

func GetChildrenRoleIdsByRoleId(ctx context.Context, roleId interface{}, withself ...bool) []interface{} {
	with := false
	if len(withself) > 0 {
		with = withself[0]
	}
	return utils.NewTree().Init(getRoles(ctx)).GetChildrenIds(roleId, with)
}

func getRoles(ctx context.Context) []map[string]interface{} {
	rows, e := database.Db.GetDefaultDb(ctx).Query("select id,pid,name from admin_role")

	if e != nil {
		panic(e)
	}

	return rows
}
